const router = require('express').Router()
const bcrypt = require('bcryptjs')
const { to } = require('await-to-js')
const baseUrl = require('../../../common/baseUrl')
const status_code = require('../../../common/status_code')
const db = require('../../../db/async-db')
const Bee = require('../../../common/bee/bee')
const defaultAvatarUrl = baseUrl + '/static/avatar/default-avatar.jpg'

router.post('/register', async (req, resp) => {
  // 错误处理
  const handleError = (errCode, error) => {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 参数错误处理
  const { account, pwd } = req.body
  if (!Bee.StringUtils.isUsername(account) || !Bee.StringUtils.isPassword(pwd))
    return handleError(10003)

  // 查询要注册的账号是否存在
  const [selectUserAccountError, selectUserAccount] = await to(
    db.query('SELECT account FROM users WHERE account=?', [account])
  )
  if (selectUserAccountError || !selectUserAccount)
    return handleError(-1, selectUserAccountError)
  // 存在就不能注册
  if (selectUserAccount.length > 0)
    return handleError(60012, selectUserAccountError)

  // 开始注册 -----------------------------------------
  // 生成salt的迭代次数
  const saltRounds = 10
  // 随机生成salt
  const salt = bcrypt.genSaltSync(saltRounds)
  // 生成密码加密后的值
  const saltPassword = bcrypt.hashSync(pwd, salt)

  // 插入用户注册表
  const [insertUserError, insertUser] = await to(
    db.query(
      'INSERT INTO users (account, pwd, created_time) VALUES (?,?, NOW())',
      [account, saltPassword]
    )
  )
  if (insertUserError || !insertUser) return handleError(-1, insertUserError)

  // 插入成功
  if (insertUser.affectedRows > 0) {
    // 插入用户信息表
    const [insertUserInfoError, insertUserInfo] = await to(
      db.query(
        'INSERT INTO userinfo (id, account, avatar_url, created_time, info_updated_time) VALUES (?, ?, ?, NOW(), NOW())',
        [insertUser.insertId, account, defaultAvatarUrl]
      )
    )
    if (insertUserInfoError || !insertUserInfo)
      return handleError(-1, insertUserInfoError)

    resp.json({
      code: 0,
      msg: status_code['0'],
    })
  } else {
    return handleError(-1)
  }
})

module.exports = router
